import axios from 'axios';
import QS from 'qs';
import { message } from 'ant-design-vue';
const instance = axios.create({
    // baseURL: import.meta.env.PROD ? 'https://admin.zkbaice.cn:9528' : '',
    baseURL: '',
    timeout: 60000,
})
import {decryptData } from '@/utils/decrypte.js';
import { addPending, removePending } from '@/utils/requestCancel.js';

function showError (err) {
    let params = {}
    if(err?.response?.data) {
        console.log('请求出错1', err);
        if(err?.response?.data?.status) {
            params= {
                status: err?.response?.data.status,
                message: err?.response?.data.message,
            }
        } else {
            params= {
                status: err?.status,
                message: err?.message,
            }
        }
        message.error(JSON.stringify(params));
    } else {
        console.log('请求出错2', err);
        params= {
          status: err?.status,
          message: err?.message,
        }
        message.error(JSON.stringify(params));
    }
}

// 添加请求拦截器
instance.interceptors.request.use(async(config) => {
    addPending(config);
    console.log('请求拦截器', config);
    
    const user = JSON.parse(localStorage.getItem('user'));
    if (user?.accessToken) {
        config.headers.Authorization = `Bearer ${user.accessToken}`;
    }
    return config;
}, (error) => {
    showError(error)
    return Promise.reject(error);
})

// 添加响应拦截器
instance.interceptors.response.use((response) => {
    removePending(response.config);
    // console.log('响应拦截器2233', response);
    
    // if(import.meta.env.PROD) {
    //     return decryptData(response.data.data);
    // }
    console.log('响应拦截器成功解密后的', decryptData(response.data.data));
    // console.log('响应拦截器成功解密后的', response.data.data);
    return decryptData(response.data.data);
    // return response.data.data;
}, async (error) => {
    error.config && removePending(error.config);
    
    if (error.name === 'AbortError' || error.code === 'ERR_CANCELED') {
        console.log('请求已被取消');
        return Promise.reject(new Error('请求已被取消'));
    }
    
    console.log('响应拦截器报错', error);
    const responseData = error?.response?.data || {};
    const status = responseData.status;
    const messageInfo = responseData.message;
    if(Number(status) === 401) {
        message.error(JSON.stringify(messageInfo));
        const origin = window.location.origin;
        window.location.href = `${origin}/login`;
        return Promise.reject(messageInfo);
    }
    
    showError(error);
    return Promise.reject(error);
});

const POSTJSON = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        instance.post(url, params, {
            headers: {
                'Content-Type': 'application/json'
            },
            ...config
        }).then((res) => {
            resolve(res);
        }).catch((err) => {
            console.log('POSTJSON error', err);
            reject(err);
        })
    })
}

const PUT = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        instance.put(url, params, {
            headers: {
                'Content-Type': 'application/json'
            },
            ...config
        }).then((res) => {
            resolve(res);
        }).catch((err) => {
            reject(err);
        })
    })
}

const GET = (url, params={}, config = {}) => {
    return new Promise((resolve, reject) => {
        instance.get(url, { params, ...config }).then((res) => {
            resolve(res);
        }).catch((err) => {
            reject(err);
        })
    })
}

const PATCH = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        instance.patch(url, params, {...config }).then((res) => {
            resolve(res);
        }).catch((err) => {
            reject(err);
        })
    })
}

const DELETE = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        instance.delete(url, params, {...config }).then((res) => {
            resolve(res);
        }).catch((err) => {
            reject(err);
        })
    })
}

const POSTFROM = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        instance.get(url, QS.stringify(params), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            ...config
        }).then((res) => {
            resolve(res);
        }).catch((err) => {
            reject(err);
        })
    })
}

export default {
    POSTJSON,
    GET,
    POSTFROM,
    PUT,
    PATCH,
    DELETE,
}